<template>
    <eui-page-frame topHeight="260" withOutBorder="true">
        <template #top>
            <view class="content-img">
                <eui-navbar ref="EuiNavBar" title="无订单收货":option="nbOption" @menuFunc="onClickMenuFunc" :storeName="getRelatedName('rdsStores', sUserStore)"
                    :storeId="sUserStore" color="#000000" backgroundColor="#FFFFFF" @onClickStore="clickStore">
                </eui-navbar>
                <view class="top-view">
                    <eui-search-bar ref="RdsSearchBar" v-model="searchText" placeholder="请输入商品条码、编码、订单号、供应商"
                        leftIcon="icon-saoyisao" @confirm="searchConfirm" @leftIconClick="scanCode" radius="30"
                        showFilter="true">
                        <template v-slot:searchFields>
                            <view class="search-fields">
                                <view class="center">
                                    <eui-card-input v-model="formData.c_status" title="单据状态" placeholder="请选择单据状态"
                                        :range="getDictSelectList('IO类单据状态')" type="radio" />
                                    <eui-card-input v-model="formData.c_provider" title="供应商" type="text"
                                        placeholder="请输入供应商编码" />
                                    <eui-card-input v-model="formData.c_mk_dt_s" title="开始日期" type="date"
                                        placeholder="请选择开始日期" rightIconType="clear" @iconClick="clear"
                                        singleTag="c_mk_dt_s" />
                                    <eui-card-input v-model="formData.c_mk_dt_e" title="结束日期" type="date"
                                        placeholder="请选择结束日期" rightIconType="clear" @iconClick="clear"
                                        singleTag="c_mk_dt_e" />
                                </view>
                                <view class="bottom flex-1 flex">
                                    <eui-button type="max" title="重置" singleTag="reset" @buttonClick="confirm" />
                                    <eui-button type="max" title="确认" singleTag="fix" @buttonClick="confirm" />
                                </view>
                            </view>
                        </template>
                    </eui-search-bar>
                </view>
            </view>
        </template>
        <eui-page-content>
            <eui-virtual-list refresher="true" :origList="dataList" isBottom="true" type="list" v-model="dataList"
                :title="false" templateTitle="" @itemClick="templateClick" @onRefresh="billList" @lower="templateLower"
                isImage :refresher="true">
                <template v-slot:list="scope">
                    <!--                    <eui-text v-model="scope.c_po_id" type="id"/>-->
                    <!-- <eui-text type="status" :value="getDictName('收发货状态', scope.c_d_status)" class="" /> -->
                    <eui-text v-model="scope.c_store_id" :name="getRelatedName('rdsStores', scope.c_store_id)"
                        type="titlename" title="目的机构" occupy />
                    <eui-text v-model="scope.c_provider" :name="getRelatedName('rdsProviders', scope.c_provider)"
                        type="titlename" title="供应商" occupy />
                    <!-- <eui-text v-model="scope.c_adno" :name="getRelatedName('rdsDeparts',scope.c_adno)" type="titlename" title="部门" occupy style="grid-template-columns: 100%;"/> -->
                    <eui-text v-model="scope.c_mk_userno" :name="getRelatedName('rdsUsers', scope.c_mk_userno)"
                        type="titlename" title="录入" />
                    <eui-text v-model="scope.c_mk_dt" type="rdstime" />
                    <eui-text v-model="scope.c_au_userno" type="titlename" title="审核"
                        :name="getRelatedName('rdsUsers', scope.c_au_userno)" v-if="scope.c_status === '3'" />
                    <eui-text v-model="scope.c_au_dt" type="rdstime" v-if="scope.c_status === '3'" />
                </template>
                <template v-slot:bottom="scope">
                    <view v-if="scope.c_status === '0' && scope.c_approve_status === '1'">
                        <eui-button :modelValue="scope" type="max" single-tag="submit" title="收货"
                            @buttonClick="buttonClick" />
                    </view>
                    <view v-if="scope.c_status === '0' && scope.c_approve_status === '1'">
                        <eui-button :modelValue="scope" type="max2" single-tag="audit"
                            :title="sysConfig.isApprove ? '审批' : '审核'" @buttonClick="buttonClick" />
                    </view>
                    <view v-if="['3', '8', '9'].includes(scope.c_status) || ['2'].includes(scope.c_approve_status)">
                        <eui-button :modelValue="scope" type="max" single-tag="detail" title="收货详情"
                            @buttonClick="buttonClick" />
                    </view>
                </template>
            </eui-virtual-list>
        </eui-page-content>
        <!--            <rds-list-template type="list" v-model="dateList" :title="false" templateTitle="" @click="templateClick"-->
        <!--                               @onRefresh="billList" @lower="templateLower" isImage :refresher="true">-->
        <!--                <template v-slot:list="scope">-->
        <!--                    <rds-text v-model="scope.c_id" type="id" occupy></rds-text>-->
        <!--                    <rds-text v-model="scope.c_store_id" :name="getName('rdsStores', scope.c_store_id)" type="titlename"-->
        <!--                              title="目的机构" occupy style="grid-template-columns: 100%;"></rds-text>-->
        <!--                    <rds-text v-model="scope.c_provider" :name="getName('rdsProviders', scope.c_provider)"-->
        <!--                              type="titlename" title="供应商" occupy style="grid-template-columns: 100%;"></rds-text>-->
        <!--                    <rds-text v-model="scope.c_mk_userno" :name="getName('rdsUsers', scope.c_mk_userno)"-->
        <!--                              type="titlename" title="录入"></rds-text>-->
        <!--                    <rds-text v-model="scope.c_mk_dt" type="rdstime"></rds-text>-->
        <!--                    <rds-text v-model="scope.c_au_userno" type="titlename" title="审核"-->
        <!--                              :name="getName('rdsUsers', scope.c_au_userno)" v-if="scope.c_status == '3'"></rds-text>-->
        <!--                    <rds-text v-model="scope.c_au_dt" type="rdstime" v-if="scope.c_status == '3'"></rds-text>-->
        <!--                </template>-->
        <!--                <template v-slot:bottem="scope">-->
        <!--                    <rds-button type="submit" v-if="scope.c_status == '0'" title="收货" v-model="scope"/>-->
        <!--                    <rds-button type="audit" v-if="scope.c_status == '0'" title="审核" v-model="scope"/>-->
        <!--                    &lt;!&ndash; <rds-button type="cancel" title="作废" v-model="scope"-->
        <!--                        v-if="scope.c_status == '0' && (scope.c_approve_status == '1' || scope.c_approve_status == '4')" /> &ndash;&gt;-->
        <!--                    <rds-button type="submit" v-if="['3', '8', '9'].includes(scope.c_status)" title="详情"-->
        <!--                                v-model="scope"/>-->
        <!--                </template>-->
        <!--            </rds-list-template>-->
    </eui-page-frame>
</template>

<script setup type="ts">
import { ref, reactive, onMounted } from 'vue';
import dateRangUtil from '../../../common/dateRangUtil';
import service from '@/common/service';
import { getRelatedName, getDictSelectList } from '../components/RelatedName.js';
import { getRdsUrl, rdsRequest } from '@/hooks/rdsServices';
import { mapState, mapMutations } from 'vuex'
import { getRdsSysConfig, init } from '@/hooks/init'
import { useMainStore } from "@/store/modules/store";
import { useLoginStore } from "@/store/modules/useLoginStore";
import { onLoad } from "@dcloudio/uni-app";
import Enjoy from "@/common/enjoy";

const rdsUrl = getRdsUrl();
const mainStore = useMainStore();
const { loginInfo } = mainStore;
const loginStore = useLoginStore();
const sUserStore = ref(''); // 用户默认机构编码


const CurrentPage = ref(1); //第几页
const PageSize = ref(10); //每页10条
const RowsCount = ref(0); //总条数
const PageCount = ref(1); //总页数
const searchText = ref(''); // true允许页面编辑
const sysConfig = ref({
    isApprove: '',//商品验收单是否审批
});

const EuiNavBar = ref(null);
const RdsSearchBar = ref(null);
// 查询表单
const formData = ref({
    c_mk_dt_s: (dateRangUtil.getLast1Month())[0],
    c_mk_dt_e: (dateRangUtil.getLast1Month())[1],
    c_provider: '',
    c_status: '0',
});
const dataList = ref([]);
const nbOption = ref({
  items: [
    {title: '新增收货', onClick: 'onClickNewCount', icon: 'plusempty'},
  ]
})

onLoad(async () => {
    await init()
    console.log('loginInfo', loginInfo);
    sUserStore.value = loginInfo.sUserStore;
    service.enjoyShowLoading('正在加载...');
    await billList();
    service.enjoyHideLoading();
    await getSysConfig();
})

const getSysConfig = async () => {
    sysConfig.value.isApprove = await getRdsSysConfig("单据是否审批", "商品验收单") === '是';
};
const SelectionChanged = async (type, item) => {
    console.log("type,item", type, item)
    switch (type) {
        case 'c_store_id':
            // 更新机构信息
            sUserStore.value = item.c_store_id;
            await billList();
            break;
    }
};
defineExpose({
    SelectionChanged
});
const scanCode = () => {
    uni.scanCode({
        success: function (res) {
            if (res.result) {
                searchText.value = res.result;
                billList();
            }
        },
    });
}
const clickStore = () => {
    let params = Enjoy.GetDialogParms();
    params.CallBack = SelectionStoreChanged;
    params.SelectionType = "机构选择";
    params.SelectedItems = sUserStore.value;
	params.IsStatust = "开业准备,正常营业";
    Enjoy.OpenDialog(params)
}
const SelectionStoreChanged = (event) => {
    if (event.SelectionType == '机构选择') {
        // 更新机构信息
        sUserStore.value = event.BackParms.Key;
    }
    // 按新条件获取数据
    billList();
}
const templateClick = async (e) => {
    console.log('click click', e);
    const { item, index } = e;
    await uni.navigateTo({
        url: './edit?c_id=' + item.c_id + '&storeId=' + item.c_rec_store_id
    });
};
const billList = async (e) => {
    if (!e) {
        CurrentPage.value = 1;
    }
    service.enjoyShowLoading('正在加载...');
    const req = {
        IsNotPage: false,
        CurrentPage: CurrentPage.value,
        PageSize: PageSize.value,
        UserNo: loginInfo.sUser,
        WhereList: [
            { c_col: "c_store_id", c_oper: "等于", c_value: sUserStore.value, c_logic: "而且" },
            {
                c_col: "c_mk_dt",
                c_oper: "大于等于",
                c_value: formData.value.c_mk_dt_s,
                c_logic: "而且",
                c_col_dtype: "System.DateTime"
            },
            {
                c_col: "c_mk_dt",
                c_oper: "小于等于",
                c_value: formData.value.c_mk_dt_e,
                c_logic: "而且",
                c_col_dtype: "System.DateTime"
            },
            { c_col: "c_po_type", c_oper: "为空", c_value: '', c_logic: "而且" },
            formData.value.c_provider ? {
                c_col: "c_provider",
                c_oper: "等于",
                c_value: formData.value.c_provider,
                c_logic: "而且"
            } : {},
            { c_col: "c_po_id", c_oper: "为空", c_value: '', c_logic: "而且" },
            formData.value.c_status ? {
                c_col: "c_status",
                c_oper: "等于",
                c_value: formData.value.c_status,
                c_logic: "而且"
            } : {},
            // { c_col: "c_src_id", c_oper: "不为空", c_value: '', c_logic: "而且" },
        ]
    }
    if (searchText.value) {
        let strLength = searchText.value.length;
        if (strLength > 6) {
            //判断是否包含英文
            const flag = await containsLetters(searchText.value);
            if (!flag) {
                strLength = 7;
            }
        }
        switch (strLength) {
            case 6://供应商
                req.WhereList.push({
                    c_col: "c_provider",
                    c_oper: "等于",
                    c_value: searchText.value,
                    c_logic: "而且",
                });
                break;
            case 7: //商品编码
                req.WhereList.push({
                    c_col: "c_gcode",
                    c_oper: "等于",
                    c_value: searchText.value,
                    c_logic: "而且",
                });
                break;
            // case 13://订单号
            // 	req.WhereList.push({
            // 		c_col: "c_po_id",
            // 		c_oper: "等于",
            // 		c_value: searchText.value,
            // 		c_logic: "而且",
            // 	});
            // 	break;
            default:
                req.WhereList.push({
                    c_col: "c_gcode",
                    c_oper: "等于",
                    c_value: searchText.value,
                    c_logic: "而且",
                });
                break;
        }
    }

    const result = await rdsRequest(rdsUrl.scApi, '商品验收单', 'EnjoyQueryList', req, '701');
    CurrentPage.value = result.CurrentPage; //第几页
    PageSize.value = result.PageSize; //每页10条
    RowsCount.value = result.RowsCount; //总条数
    PageCount.value = result.PageCount; //总页数
    if (result.CurrentPage == 1) {
        dataList.value = result.ReturnObject;
    } else {
        dataList.value = dataList.value.concat(result.ReturnObject);
    }
    service.enjoyHideLoading();
};
// 新增单据
const onClickMenuFunc = async (e) => {
  switch (e) {
    case 'onClickNewCount':
      setTimeout(() => {
        EuiNavBar.value.closeDrawer();
      },1200);
      uni.navigateTo({
        url: './edit?storeId=' + sUserStore.value
      });
      break;
  }
}
// 上拉加载更多
const templateLower = async () => {
    if (CurrentPage.value < PageCount.value) {
        CurrentPage.value = CurrentPage.value + 1;
        await billList(true);
    }
};
const searchConfirm = async (e) => {
    searchText.value = e.value.toUpperCase();
    await billList();
};
const clear = (e) => {
    switch (e) {
        case 'c_mk_dt_s':
            formData.value.c_mk_dt_s = '';
            break;
        case 'c_mk_dt_e':
            formData.value.c_mk_dt_e = '';
            break;
    }
}
const confirm = async (t) => {
    let { singleTag } = t;
    switch (singleTag) {
        case 'reset':
            formData.value.c_mk_dt_s = (dateRangUtil.getLast1Month())[0];
            formData.value.c_mk_dt_e = (dateRangUtil.getLast1Month())[1];
            formData.value.c_provider = '';
            formData.value.c_po_id = '';
            formData.value.c_status = '0';
            break;
        case 'fix':
            await billList();
            // 关闭弹出层
            RdsSearchBar.value.closeDrawer();
            break;
    }
};
//判断是否包含英文
const containsLetters = async (str) => {
    return /[a-zA-Z]/.test(str);
};
const buttonClick = async (e) => {
    let { singleTag, modelValue, type } = e;

    const req = {
        BillId: modelValue.c_id,
        UserNo: loginInfo.sUser,
    }
    switch (singleTag) {
        case 'cancel':
            if (modelValue.c_status == "0") {
                await uni.showModal({
                    title: ' 提示',
                    content: '请确认，作废单据[' + req.BillId + ']?',
                    showCancel: true,
                    success: (res) => {
                        if (res.confirm) {
                        }
                    }
                });
            }
            break;
        case 'audit':
            if (['3', '8', '9'].includes(modelValue.c_status)) {
                // 审核状态为已审核或已作废的单据只允许查看；
                await templateClick(v);
            } else {
                if (modelValue.c_status == '0') {
                    await uni.showModal({
                        title: ' 提示',
                        content: '请确认，审核单据[' + req.BillId + ']?',
                        showCancel: true,
                        success: async (res) => {
                            if (res.confirm) {
                                service.enjoyShowLoading('正在审核...');
                                const result = await rdsRequest(rdsUrl.scApi, '商品验收单', 'EnjoyBillAudit', req, '701');
                                service.enjoyHideLoading();
                                await uni.showToast({
                                    duration: 3500,
                                    icon: 'none',
                                    title: ' 审核成功！'
                                });
                                await billList();
                            }
                        }
                    });
                }
            }
            break;
        case 'submit':
            await uni.navigateTo({
                url: './edit?c_id=' + modelValue.c_id + '&storeId=' + sUserStore.value
            });
            break;
        case 'detail':
            await uni.navigateTo({
                url: './edit?c_id=' + modelValue.c_id + '&storeId=' + sUserStore.value
            });
            break;
    }
}
</script>

<style lang="scss" scoped>
@import '@/static/font/enjoyicon/iconfont.css';
@import '../../../main.scss';

.custom-menu {
    border-top: 1px solid rgba(0, 0, 0, .1);
    display: flex;
    flex: 1;
    width: 100%;
    justify-content: flex-start;
}

.popup-icon-btn {
    display: flex;
    padding: 10px;
    margin: 5px;
    color: #333333;
    text-align: center;
    flex-direction: column;
}

.popup-icon-btn uni-icon {
    margin: 0 auto;
    background: #ffffff;
    border-radius: 50%;
    font-size: 1.2em;
    width: 42px;
    height: 42px;
    line-height: 42px;
    text-align: center;
}

.popup-icon-btn uni-text {
    font-size: 0.8em;
    padding: 0.2em 0;
    line-height: 1.4em;
    width: 52px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}


.top-view {
    width: 100%;
    height: 88rpx;
    background: #FFFFFF;
}

.main-view {
    flex: 1;
    flex-direction: column;
}

.search-fields {
    width: 100%;
    background: #FFFFFF;
    position: relative;

    .bottom {
        background: #ffffff;
        border-top: 1rpx solid $uni-line-color;
        display: flex;
        justify-content: center;
        padding: 20rpx;
    }
}
</style>
